/*
 *区域管理功能模块
 */
define("func/areaManagement",[
    "leaflet",
    "func/base",
    "control/panel",
    "control/draw",
    "control/playback",
    "control/loading",
    "plugins/mcscroll",
    // "plugins/my97DatePicker",
    "data/ajax",
],function(L){
    L.ICT.Func.add("AreaManageMent",{
        Class:L.Class.extend({
            initialize:function(){
                this.secondmenu=L.ict.app.secondmenu;
                this.menuid='ict_secmenu_main_qygl';
                this.config=Project_ParamConfig.tshfConfig;
                this.ictmap=L.ict.app.ictmap;
                this.ajax=new L.ICT.Ajax();
                this._areaAddPanel=null;
                this._areaListPanel=null;
                this._areaEditPanel=null;
                this._drawPopanel=null;
                this._layer=null;
                this._palyback=null;
                this._arealistData=null;
            },
            
            start: function() {
                this.secondmenu.mainmenu.deactiveMenuExceptOne(this.menuid);
                if (!this.secondmenu.submenu.has(this.menuid)) {
                    this.secondmenu.submenu.add(this.menuid, this.getSubMenuHTML());
                }
                this.secondmenu.submenu.show(this.menuid);
                this._initSubMenuEvts();

            },

            stop: function() {
                if (this._areaAddPanel) this._areaAddPanel.remove(false);
                if (this._areaListPanel) this._areaListPanel.remove(false);
                if (this._areaEditPanel) this._areaEdittPanel.remove(false);
                if (this._drawPopPanel) this._drawPopPanel.remove(false);
                if (this._layer) this._layer.remove();
                if(this.ictmap.map.hasLayer(this._locatelayer)){
                  this.ictmap.map.removeLayer(this._locatelayer);
                }
                this._areaAddPanel = null;
                this._areaListPanel = null;
                this._areaEditPanel = null;
                this._drawPopPanel = null;
                this._layer = null;

                this.ictmap.deactivate();
                // this.menu.submenu.destory(this.menuid);
                // this.menu.mainmenu.deactiveMenu(this.menuid);

            },

            //获取子菜单HTML
            getSubMenuHTML: function() {
                var html = [];
                html.push('<ul class="submenu_areaManage">');
                html.push('<li class="menu_item areaList"><a href="#">区域列表</label></li>');
                html.push('<li class="menu_item areaAdd"><a href="#">添加区域</label></li>');
                html.push('</ul>');
                return html.join("");

            },

            //初始化子菜单点击事件
            _initSubMenuEvts: function() {
                var self = this;
                var $menuContainer = this.secondmenu.getContainer();
                // console.log($menuContainer)
                $menuContainer.find(".menu_item").on("click", function(event) {
                    event.stopPropagation();
                    // console.log(event.currentTarget)
                    // console.log(this)
                    var $this = $(this);
                    if ($this.hasClass("areaList")) {
                        // 区域列表 
                        if (self._areaListPanel) {
                            self._areaListPanel.remove(false);
                            self._areaListPanel = null;
                        }
                        self.areaList();
                        self.secondmenu.submenu.hide();

                    } else if ($this.hasClass("areaAdd")) {
                        //添加区域
                        
                        if (self._areaAddPanel) {
                            self._areaAddPanel.remove(false);
                            self._areaAddPanel = null;
                        }
                        self.addArea();
                        // self.areaEdit();
                        self.secondmenu.submenu.hide();
                    }
                });

            },

            //弹出添加区域窗口
            addArea: function() {
                var options = {
                    title: "添加区域",
                    width: 300,
                    height: 310,
                    top: 100,
                    left: 200,
                    contentHTML: this.getAreaHtml()
                };
                var pop = this._areaAddPanel = new L.ICT.PopPanel(options);
                //窗口关闭事件
                this._areaAddPanel.on("popPanelRemove", function() {
                    if(this._drawPopPanel) {
                        this._drawPopPanel.remove();
                    }
                    if(this.ictmap.map.hasLayer(this._layer)) {
                        this.ictmap.map.removeLayer(this._layer);
                    }
                    this._areaAddPanel = null;
                    this.stop();

                }, this);
                pop.show();
                this._initAreaEvts();
                // this.ictmap.activate(L.ICT.MapMouseState.CIRCLE, this._drawCallback, null, this);
            },

            //初始化添加区域事件
            _initAreaEvts: function() {
                var self = this;
                var $container = this._areaAddPanel.getContainer().find(".areaAddContainer");
                var $msg = $container.find(".msg");
                var $areaNameText=$container.find(".areaText").val()
                // this._loading = new L.ICT.Control.Loading().addTo(this._areaAddPanel.getContainer().find(".container-content"));
                console.log($areaNameText,$msg)
                //绘制事件
                // console.log( $container.find(".rect"))
                $(".form-group>div").on("click", function () {
                    if(self.ictmap.map.hasLayer(self._layer)) {
                        self.ictmap.map.removeLayer(self._layer);
                    }
                    if(self._drawPopPanel) {
                        self._drawPopPanel.remove();
                    }
                    // console.log(q)
                    var type = $(this).attr("class");
                    console.log(type);
                    if(type == "circle") {
                        self.ictmap.activate(L.ICT.MapMouseState.CIRCLE, self._drawCallback, null, self);
                    } else if(type == "rect") {
                        self.ictmap.activate(L.ICT.MapMouseState.RECTANGLE, self._drawCallback, null, self);
                    } else if(type == "polygon") {
                        self.ictmap.activate(L.ICT.MapMouseState.POLYGON, self._drawCallback, null, self);
                    } else if(type == "sector") {
                        self.ictmap.activate(L.ICT.MapMouseState.SECTOR, self._drawCallback, null, self);
                    }
                });
                $container.find(".add_okbtn").on("click",function(){
                    
                    if(self._layer==null){
                        $msg.html("请绘制区域!")
                        return;
                    }
                    if($areaNameText==""){
                        $msg.html("请输入区域名称!");
                        return;
                    }
                })
                
            },
            //弹出区域列表窗口
            areaList: function() {
                var self=this;
                var options = {
                    title: "区域列表",
                    width: 220,
                    height: 180,
                    top: 100,
                    left: 200,
                    contentHTML: this.getListHtml()
                };

                var pop = this._areaListPanel = new L.ICT.PopPanel(options);
                //窗口关闭事件
                this._areaListPanel.on("popPanelRemove", function() {
                    if(this._drawPopPanel) {
                        this._drawPopPanel.remove();
                    }
                    if(this.ictmap.map.hasLayer(this._layer)) {
                        this.ictmap.map.removeLayer(this._layer);
                    }
                    this._areaListPanel = null;
                    
                    this.stop();
                }, this);
                pop.show();
                this._initAreaListEvts();
                // this.ictmap.activate(L.ICT.MapMouseState.RECTANGLE, this._drawCallback, null, this);
            },
            _initAreaListEvts: function() {
                var self=this;
                var url=this.config.areaListUrl;
                var data={
                        type:300,
                        pageid:1,
                        pagecount:100,
                        show_status:1,
                };
                this.ajax.post(url, data, true, self, function (res, err){                            
                        self.showAreaListRes(res && res.msg && res.msg.areas || []);         
                        self.areaSetting();
                 });

                 
              },
              areaSetting:function(){
                var self=this
                var $container=this._areaListPanel.getContainer().find(".area_list_container");
                $container.find(".locate").on("click",function(e){
                    var id=$(e.currentTarget).parent().parent().data("id");
                    console.log(id);
                    var areaInfo = this.getAreaDataById(id);
                    console.log(areaInfo);
                    if (!areaInfo) return;
                    if(this.ictmap.map.hasLayer(this._locatelayer)){
                      this.ictmap.map.removeLayer(this._locatelayer);
                    }
                    // 定位图层
                      this._locatelayer = L.ict.app.util.tool.convertGeoJsonToLeafletLayer(areaInfo);
                      this.ictmap.map.addLayer(this._locatelayer);
                      this.ictmap.map.fitBounds(this._locatelayer.getBounds());
                   
                }.bind(this));
                $container.find(".edit").on("click",function(){
                    self.areaEdit();
                })
                $container.find(".delete").on("click",function(event){
                    // var url=this.config
                    var targetId = $(this).parent().parent().data("id");
                    data={};
                    data.type=300;
                    data.id=targetId;
                   console.log($(this).parent().parent())
                    
                    this.ajax.post(url,data,true,this,function(res){
                        if(res){
                            if(res.state !== 1){
                                // this.dialog.alert("提示",res.msg.error);
                            }else{
                                $(this).parent().parent().remove();
                            }
                        }
                   });
                   
                    
                })
              },
             //弹出区域编辑窗口
             areaEdit: function() {
                var options = {
                    title: "区域编辑",
                    width: 250,
                    height: 200,
                    top: 100,
                    left: 600,
                    contentHTML: this.getEditHtml()
                };
                var pop = this._areaEditPanel = new L.ICT.PopPanel(options);
                //窗口关闭事件
                this._areaEditPanel.on("popPanelRemove", function() {
                    this._areaEditPanel = null;
                    this.stop();

                }, this);
                pop.show();
                this._initAreaEditEvts()
            },
            _initAreaEditEvts:function(){
                // console.log(1)
                var $container=this._areaEditPanel.getContainer().find(".edit_container");
                var $msg=$container.find(".msg");
                var $inputText=$container.find(".areaText").val();
                console.log($container,$msg,$inputText)
                $container.find(".edit_ok").on("click",function(){
                    if($inputText===""){
                        $msg.html("请输入区域名称");
                    }
                })
            },
            //获取添加区域HTML
            getAreaHtml: function() {
                var html = [];
                html.push('<div class="areaAddContainer">');
                html.push('<fieldset class="drawDiv">');
                html.push('<legend class="common_draw_title">绘制区域：</legend> ');
                html.push('<div class="form-group">');
                html.push('<div class="rect"><label><img src="themes/images/frame/ico_rect.png">矩形</label></div>');
                html.push('<div class="circle"><label><img src="themes/images/frame/ico_circle.png">圆形</label></div>');
                html.push('<div class="polygon"><label><img src="themes/images/frame/ico_ployon.png">多边形</label></div>');
                html.push('<div class="sector"><label><img src="themes/images/frame/ico_sector.png">扇环形</label></div>');
                html.push('</div>');
                html.push('</fieldset>');
                html.push('<div class="area_name">');
                html.push("<p>区域名称：</p>")
                html.push('<input type="text" class="areaText">');
                html.push('</div>');
                html.push('<label><input type="checkbox">设置为敏感区域</label>');
                html.push('<p class="msg"></p>');
                html.push('<div class="btnDiv"><button type="button" class="btn add_okbtn">确定</button></div>');
                html.push('</div>');
                return html.join('');

            },
           
            //获取区域列表HTML
            getListHtml: function() {

                var html = [];
                html.push('<div class="area_list_container">');
                // for (var i = 0, len = data.length; i < len; i++){
                //     html.push('<li data-id="'+data[i].properties.id+'"">')
                //     html.push('<div class="mg_bs">');
                //     html.push('<i>敏感</i>');
                //     html.push('<span class="area_list">'+data[i].properties.name+'</span>');
                //     html.push('</div>');
                //     html.push('<div class="area_setting">');
                //     html.push('<span class="locate"><img src="./themes/images/new/icon_locate.png" title="定位"></span>');
                //     html.push('<span class="edit"><img src="./themes/images/new/icon_edit.png" title="编辑"></span>');
                //     html.push('<span class="delete"><img src="./themes/images/new/icon_clear.png" title="删除"></span>');
                //     html.push('</div>');
                //     html.push("</li>");
                // }
                html.push('</ul>');
                html.push('</div>');
                return html.join('');
                console.log(html)
            },
             showAreaListRes(data){
                var $arealist =$(".area_list_container");
                console.log($arealist.find(".list_container"));
                this._arealistData = data;
                // console.log(data)
                var html = [];
                html.push('<ul class="list_container">');
                for (var i = 0, len = data.length; i < len; i++){
                    html.push('<li data-id="'+data[i]['properties']['id']+'"">')
                    html.push('<div class="mg_bs">');
                    html.push('<i>敏感</i>');
                    html.push('<span class="area_list">'+data[i]['properties']['name']+'</span>');
                    html.push('</div>');
                    html.push('<div class="area_setting">');
                    html.push('<span class="locate"><img src="./themes/images/new/icon_locate.png" title="定位"></span>');
                    html.push('<span class="edit"><img src="./themes/images/new/icon_edit.png" title="编辑"></span>');
                    html.push('<span class="delete"><img src="./themes/images/new/icon_clear.png" title="删除"></span>');
                    html.push('</div>');
                    html.push("</li>");
                }
                html.push('</ul>');
                $arealist.html(html.join(''))
                $arealist.find(".list_container").mCustomScrollbar({ theme: "minimal-dark" });    
            },
            // 获取区域编辑窗口
            getEditHtml:function(){
                var html=[];
                html.push('<div class="edit_container">');
                html.push('<div class="area_name"><label>区域名称:<input type="text"class="areaText"></label></div>');
                html.push('<div class="mg_setting"><label><input type="checkbox" >设置为敏感区域</label></div>');
                html.push('<p class="msg"></p>')
                html.push('<div class="btnDiv"><button class="edit_ok">确定</button></div>');
                html.push('</div>');
                return html.join('');
            },
            getAreaDataById:function (id) {
                if (this._arealistData && this._arealistData.length) {
                    for (var i = 0, len = this._arealistData.length; i < len; i++){
                        if (this._arealistData[i]['properties']['id'] === Number(id)) {
                            return this._arealistData[i];
                        }
                    }
                }
            },

            //绘图回调
            _drawCallback: function (e) {
                var layer = e.layer;
                var layerType = e.layerType;
                this.ictmap.map.addLayer(layer);
                // 检查范围是否越界
                var bounds = layer.getBounds();
                if (L.ict.app.util.tool.isLatLngsOutExtend(bounds)){
                    this.ictmap.map.removeLayer(layer);
                    L.ict.app.util.dialog.error('错误', '您绘制的区域超出合法范围！');
                    return;
                }
                //加图层
                this._layer = layer;
                // 弹出编辑框
                if(this._drawPopPanel) {
                    this._drawPopPanel.remove();
                }
                this._drawPopPanel = new L.ICT.DrawPopPanel(layer, layerType);
                this._drawPopPanel.on("popPanelRemove", function () {
                    this._drawPopPanel = null;
                }, this);
                this._drawPopPanel.show();
                //可编辑
                if(layer.editing) {
                    layer.editing.enable();
                    layer.on("edit", function (o) {
                        this._drawPopPanel.updateContent();
                    }, this);
                }
            },

        })

    });

})